import axios from 'axios';
import type { AxiosInstance, AxiosRequestConfig, AxiosResponse } from 'axios'
import type { InternalAxiosRequestConfig } from 'axios';
import { ElMessage } from 'element-plus';

const service: AxiosInstance = axios.create({
   baseURL: import.meta.env.VITE_API_BASE_URL,
   timeout: 5000
})

// 请求拦截器
service.interceptors.request.use(
    (config: AxiosRequestConfig) => {
        // 类型断言
        const internalConfig = config as InternalAxiosRequestConfig;
        const token = localStorage.getItem('token');
        if (token) {
            internalConfig.headers.Authorization = `${token}`;
        }
        return internalConfig;
    },
    (error) => {
        console.error('请求错误:', error);
        return Promise.reject(error);
    }
);

//响应拦截器
service.interceptors.response.use(
    (response: AxiosResponse) => {
        return response.data
    },
    (error)=>{
        let errorMessage = ''
        if(error.response){
            const status = error.response.status
            switch(status){
                case 400: 
                   errorMessage = '400 Bad Request：请求参数有误';
                   break
                case 401:
                   errorMessage = '401 Unauthorized：未授权，请先登录';
                   break
                case 403: 
                   errorMessage = '403 Forbidden：禁止访问，没有权限';
                   break
                case 404:
                   errorMessage = '404 Not Found：请求的资源不存在';
                   break
                case 500:
                   errorMessage = '500 Internal Server Error：服务器内部错误';
                   break;
                default:
                   errorMessage = `请求失败，状态码：${status}`;
            }
        }else if(error.request){
            errorMessage = '请求已发送，但没有收到响应，请检查网络连接';
        }else{
            errorMessage = '请求设置时发生错误：' + error.message;
        }
        ElMessage.error(errorMessage)
        console.error('响应错误',error)
        return Promise.reject(error)
    }
)

const request = {
    get<T>(url: string,config?: AxiosRequestConfig) : Promise<T>{
        return service.get(url,config)
    },
    post<T>(url: string,data?:any,config?: AxiosRequestConfig) : Promise<T>{
        return service.post(url,data,config)
    },
    put<T>(url: string,data?:any,config?:AxiosRequestConfig):Promise<T>{
        return service.put(url,data,config)
    },
    delete<T>(url: string,config?:AxiosRequestConfig): Promise<T>{
        return service.delete(url,config)
    }
}

export default request